package com.hnit.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hnit.web.bean.Coupons;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

/**
 * 优惠券Mapper接口
 */
@Mapper
public interface CouponsMapper extends BaseMapper<Coupons> {

    /**
     * 减少优惠券库存（乐观锁）
     * @param couponId 优惠券ID
     * @return 更新行数
     */
    @Update("UPDATE coupons SET remainingCount = remainingCount - 1, updatedTime = NOW() " +
            "WHERE couponId = #{couponId} AND remainingCount > 0")
    int decrementStock(@Param("couponId") Long couponId);

    /**
     * 增加优惠券库存（回滚用）
     * @param couponId 优惠券ID
     * @return 更新行数
     */
    @Update("UPDATE coupons SET remainingCount = remainingCount + 1, updatedTime = NOW() " +
            "WHERE couponId = #{couponId}")
    int incrementStock(@Param("couponId") Long couponId);

    /**
     * 批量同步Redis库存到数据库
     * @param couponId 优惠券ID
     * @param remainingCount 剩余库存
     * @return 更新行数
     */
    @Update("UPDATE coupons SET remainingCount = #{remainingCount}, updatedTime = NOW() " +
            "WHERE couponId = #{couponId}")
    int syncStock(@Param("couponId") Long couponId, @Param("remainingCount") Integer remainingCount);
}
